package com.emex.app.stuff.report;

import com.emex.app.shared.data.OrderPayment;
import com.emex.app.shared.data.Orders;
import com.emex.app.stuff.gui.OrderDialog;
import com.emex.app.stuff.gui.model.OrderPaymentReportTableModel;
import com.emex.app.stuff.gui.model.OrdersTableModel;
import com.emex.app.stuff.gui.model.renderer.OrderPaymentReportRenderer;
import com.emex.app.stuff.provider.OrderDataProvider;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.util.ArrayList;
import java.util.List;
import net.sf.jasperreports.engine.JasperPrint;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.report//OrderPayment//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "OrderPaymentTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.report.OrderPaymentTopComponent")
@ActionReference(path = "Menu/Отчетность" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_OrderPaymentAction",
        preferredID = "OrderPaymentTopComponent"
)
@Messages({
    "CTL_OrderPaymentAction=Отчет по оплатам",
    "CTL_OrderPaymentTopComponent=Отчет по опалатам",
    "HINT_OrderPaymentTopComponent=Отчет по оплатам"
})
public final class OrderPaymentTopComponent extends TopComponent {

    public OrderPaymentTopComponent() {
        initComponents();
        setName(Bundle.CTL_OrderPaymentTopComponent());
        setToolTipText(Bundle.HINT_OrderPaymentTopComponent());
        orderPaymentsTable.setHorizontalScrollEnabled(true);
        orderPaymentsTable.setColumnControlVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        cashLabel = new javax.swing.JLabel();
        beznalLabel = new javax.swing.JLabel();
        qiwilabel = new javax.swing.JLabel();
        cardLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        startDatePicker = new org.jdesktop.swingx.JXDatePicker();
        applyFilterButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        endDatePicker = new org.jdesktop.swingx.JXDatePicker();
        jScrollPane1 = new javax.swing.JScrollPane();
        orderPaymentsTable = new org.jdesktop.swingx.JXTable();
        printButton = new javax.swing.JButton();

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.jPanel2.border.title"))); // NOI18N

        cashLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(cashLabel, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.cashLabel.text")); // NOI18N

        beznalLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(beznalLabel, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.beznalLabel.text")); // NOI18N

        qiwilabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(qiwilabel, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.qiwilabel.text")); // NOI18N

        cardLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(cardLabel, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.cardLabel.text")); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cashLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
                    .addComponent(beznalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(qiwilabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cardLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cashLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(beznalLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(qiwilabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cardLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.jPanel1.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(applyFilterButton, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.applyFilterButton.text")); // NOI18N
        applyFilterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyFilterButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.jLabel2.text")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(startDatePicker, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(applyFilterButton))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(endDatePicker, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(applyFilterButton)
                .addContainerGap())
        );

        orderPaymentsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                orderPaymentsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(orderPaymentsTable);

        printButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/print.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(printButton, org.openide.util.NbBundle.getMessage(OrderPaymentTopComponent.class, "OrderPaymentTopComponent.printButton.text")); // NOI18N
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(printButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void applyFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyFilterButtonActionPerformed
        if (null == startDatePicker.getDate()) {
            UIUtils.showErrorMessage("Выберите дату начала");
            return;
        }
        if (null == endDatePicker.getDate()) {
            UIUtils.showErrorMessage("Выберите дату окончания");
            return;
        }
        List<OrderPayment> orders = OrderDataProvider.getInstance().getOrderPaymentsByDate(startDatePicker.getDate(), endDatePicker.getDate());
        OrderPaymentReportTableModel model = new OrderPaymentReportTableModel(orders);
        orderPaymentsTable.setModel(model);
        orderPaymentsTable.setDefaultRenderer(Double.class, new OrderPaymentReportRenderer());
        cashLabel.setText("Наличные: " + round(model.getGenNal(), 2));
        beznalLabel.setText("Без.нал.: " + round(model.getGenBeznal(), 2));
        qiwilabel.setText("QIWI: " + round(model.getGenQiwi(), 2));
        cardLabel.setText("Карта: " + round(model.getGenCard(), 2));
    }//GEN-LAST:event_applyFilterButtonActionPerformed

    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        if (orderPaymentsTable.getRowCount() > 0) {
            try {
                StringBuilder str = new StringBuilder();
                str.append(cashLabel.getText()).append("\\n")
                        .append(beznalLabel.getText()).append("\\n")
                        .append(qiwilabel.getText()).append("\\n")
                        .append(cardLabel.getText()).append("\\n");
                JasperPrint print = ReportGenerator.getInstance().generateDynamicReport(orderPaymentsTable, str.toString());
                ReportGenerator.getInstance().showReport(print);
            } catch (Exception ex) {
                UIUtils.showErrorMessage("Произошли ошибки при печати таблицы");
            }
        }
    }//GEN-LAST:event_printButtonActionPerformed

    private void orderPaymentsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_orderPaymentsTableMouseClicked
        if (evt.getClickCount() == 2) {
            OrderPayment selection = getOrderPaymentSelection();
            if (null != selection) {
                Orders orders = OrderDataProvider.getInstance().selectOrderByPrimaryKey(selection.getOrderId());
                if (null != orders) {
                    OrderDialog dialog = new OrderDialog(WindowManager.getDefault().getMainWindow(), true);
                    dialog.setOrder(orders);
                    dialog.setOrdersTableModel(new OrdersTableModel(new ArrayList<Orders>()));
                    dialog.setLocationRelativeTo(null);
                    dialog.setVisible(true);
                }
            }
        }
    }//GEN-LAST:event_orderPaymentsTableMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyFilterButton;
    private javax.swing.JLabel beznalLabel;
    private javax.swing.JLabel cardLabel;
    private javax.swing.JLabel cashLabel;
    private org.jdesktop.swingx.JXDatePicker endDatePicker;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable orderPaymentsTable;
    private javax.swing.JButton printButton;
    private javax.swing.JLabel qiwilabel;
    private org.jdesktop.swingx.JXDatePicker startDatePicker;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public double round(double value, int places) {
        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

    protected OrderPayment getOrderPaymentSelection() {
        if (orderPaymentsTable.getSelectedRow() > -1) {
            OrderPayment pos = (OrderPayment) orderPaymentsTable
                    .getValueAt(orderPaymentsTable.getSelectedRow(), -1);
            return pos;
        }
        return null;
    }
}
